package com.neiquan.backstage.platform_weixin.web.action;

import java.util.Arrays;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.neiquan.backstage.common.util.CommonResp;
import com.neiquan.backstage.platform_system_config.PlatformSystemConfigService;
import com.neiquan.backstage.pub.bsc.dao.po.PlatformSystemConfig;

import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.bean.WxMenu;
import me.chanjar.weixin.common.bean.WxMenu.WxMenuButton;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.WxMpServiceImpl;

@Controller
@RequestMapping(value = "platformWeixin", produces = { "text/json;charset=UTF-8" })
public class PlatformWeixinAction {
	@Autowired
	private PlatformSystemConfigService systemConfigService;

	@ResponseBody
	@RequestMapping("updateMenu")
	public String updateMenu() {
		PlatformSystemConfig systemConfig = systemConfigService.query();
		WxMpInMemoryConfigStorage wxMpInMemoryConfigStorage = new WxMpInMemoryConfigStorage();
		wxMpInMemoryConfigStorage.setAppId(systemConfig.getWeixinAppId());
		wxMpInMemoryConfigStorage.setSecret(systemConfig.getWeixinAppSecret());
		wxMpInMemoryConfigStorage.setToken(systemConfig.getWeixinToken());
		wxMpInMemoryConfigStorage.setAesKey(systemConfig.getWeixinEncodingAesKey());
		WxMpService wxMpService = new WxMpServiceImpl();
		wxMpService.setWxMpConfigStorage(wxMpInMemoryConfigStorage);
		WxMenu wxMenu = _buildMenu( //
				_buildButton(WxConsts.BUTTON_VIEW, "热点/干货", null, systemConfig.getWeixinH5UrlArticle()), //
				_buildButton(WxConsts.BUTTON_VIEW, "联盟成员", null, systemConfig.getWeixinH5UrlAllianceMember()), //
				_buildButton(WxConsts.BUTTON_VIEW, "创业服务", null, systemConfig.getWeixinH5UrlEntrepreneurService()) //
		);
		try {
			wxMpService.menuCreate(wxMenu);
		} catch (WxErrorException e) {
			return CommonResp.buildErrorResp(e).toJsonString();
		}
		return CommonResp.buildSuccessResp().toJsonString();
	}

	private static WxMenu _buildMenu(WxMenuButton... buttons) {
		WxMenu wxMenu = new WxMenu();
		wxMenu.setButtons(Arrays.asList(buttons));
		return wxMenu;
	}

	private static WxMenuButton _buildButton(String type, String name, String key, String url, WxMenuButton... subButtons) {
		WxMenuButton button = new WxMenuButton();
		button.setType(type);
		button.setName(name);
		button.setKey(key);
		button.setUrl(url);
		button.setSubButtons(Arrays.asList(subButtons));
		return button;
	}
}
